@echo off
chcp 65001 >nul
echo ========================================
echo fileup Docker Reset Script
echo Target Image: liured88/fileup
echo Target Container: fileup
echo External Port: 7598 -> Internal Port: 5000
echo ========================================

echo Step 0: Check Docker service status...
docker version >nul 2>&1
if errorlevel 1 goto docker_not_running
echo Docker service is running!
goto docker_ready

:docker_not_running
echo Docker service is not running!
echo Please start Docker Desktop and try again.
echo.
echo Starting Docker Desktop...
start "" "C:\Program Files\Docker\Docker\Docker Desktop.exe"
echo Waiting for Docker to start (this may take a few minutes)...
timeout /t 30 /nobreak >nul
echo Checking Docker status again...
docker version >nul 2>&1
if errorlevel 1 (
    echo Docker is still not ready. Please wait and try again manually.
    pause
    exit /b 1
)
echo Docker service is now running!

:docker_ready

echo.
echo Step 1: Build new fileup_temp image...
echo Removing existing fileup_temp image if exists...
docker rmi fileup_temp 2>nul
echo Building new fileup_temp image...
docker build -t fileup_temp .
if %errorlevel% neq 0 (
    echo Build failed!
    pause
    exit /b 1
)
echo Build successful!

echo.
echo Step 2: Remove existing fileup container...
docker ps -a | findstr "fileup" >nul
if %errorlevel% equ 0 (
    echo Stopping and removing fileup container...
    docker stop fileup 2>nul
    docker rm fileup 2>nul
    echo Container removed
) else (
    echo No fileup container found
)

echo.
echo Step 3: Remove old image and rename new image...
docker images | findstr "liured88/fileup" >nul
if %errorlevel% equ 0 (
    echo Removing old liured88/fileup image...
    docker rmi liured88/fileup 2>nul
    echo Old image removed
) else (
    echo No old liured88/fileup image found
)

echo Renaming fileup_temp to liured88/fileup...
docker tag fileup_temp liured88/fileup
if %errorlevel% neq 0 (
    echo Image rename failed!
    pause
    exit /b 1
)
docker rmi fileup_temp
echo Image rename successful!

echo.
echo Step 4: Create and start new fileup container...
echo Creating container with port mapping 7598:5000 and 4041:4040...
docker run -itd -p 7598:5000 -p 4041:4040 -v /d/bak/share:/bak/share --name fileup liured88/fileup
if %errorlevel% neq 0 (
    echo Container start failed!
    echo Checking if port 7598 is already in use...
    netstat -an | findstr ":7598" >nul
    if %errorlevel% equ 0 (
        echo Port 7598 is already in use!
    )
    pause
    exit /b 1
)
echo Container started successfully!
echo.
echo Access URLs:
echo - Local: http://localhost:7598
echo - ngrok Admin: http://localhost:4041

echo.
echo Step 5: Show container logs...
echo Press Ctrl+C to exit log view
echo ========================================
docker logs -f fileup